<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xmlns:th="http://www.thymeleaf.org">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>材料库存</title>
    <!-- Bootstrap CSS-->
    <link rel="stylesheet" href="../../static/css/lib/bootstrap3.4.1.min.css" th:href="@{/css/lib/bootstrap3.4.1.min.css}">
    <!-- Bootstrap-table CSS-->
    <link rel="stylesheet" href="../../static/css/lib/bootstrap-table.min.css" th:href="@{/css/lib/bootstrap-table.min.css}">
    <!-- jquery-ui CSS-->
    <link rel="stylesheet" href="../../static/css/lib/jquery-ui.min.css" th:href="@{/css/lib/jquery-ui.min.css}">
    <!-- select2 CSS-->
    <link rel="stylesheet" href="../../static/css/lib/select2.min.css" th:href="@{/css/lib/select2.min.css}">
    <link rel="stylesheet" href="../../static/css/lib/select2-bootstrap.min.css" th:href="@{/css/lib/select2-bootstrap.min.css}">
    <link href="../../static/css/file.css" rel="stylesheet" th:href="@{/css/file.css}">
    <link href="../../static/css/table.css" rel="stylesheet" th:href="@{/css/table.css}">
</head>

<body onload="init();">
    <div class="panel-body" style="padding-bottom:0;">
        <div class="panel panel-default">
            <div class="panel-heading">查询条件</div>
            <div class="panel-body">
                <div class="form-group" style="margin-top:15px">
                    <div class="row row-gap">
                        <label class="control-label col-sm-2 label-font" for="txt_search_item_name" title="品名/磁棒/尺寸(材质)">品名/磁棒/尺寸(材质)</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="txt_search_item_name">
                        </div>
    
                        <label class="control-label col-sm-2 label-font" for="txt_search_spec" title="规格/初R值/电阻线(线径)">规格/初R值/电阻线(线径)</label>
                        <div class="col-sm-4">
                            <input type="text" class="form-control" id="txt_search_spec">
                        </div>
                    </div>
    
                    <div class="row row-gap">
                        <div class="col-sm-offset-4" style="text-align:left;">
                            <button type="button" style="margin-left:50px" id="btn_filter" class="btn btn-primary" onclick="filter();">过滤</button>
                            <button type="button" style="margin-left:50px" id="btn_reset_filter" class="btn btn-primary" onclick="init();">重置过滤</button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    
        <div id="toolbar" class="btn-group">
            <button id="btn_add" type="button" class="btn btn-default" data-toggle="modal" onclick="InAdd();">
                <span class="glyphicon glyphicon-plus" aria-hidden="true"></span>生产出库
            </button>
            <button id="btn_export" type="button" class="btn btn-default" onclick="exportExcel();">
                <span class="glyphicon glyphicon-export" aria-hidden="true"></span>批量导出库存信息
            </button>
            <button id="btn_export2" type="button" class="btn btn-default" onclick="exportDetailExcel();">
                <span class="glyphicon glyphicon-export" aria-hidden="true"></span>批量导出库存详细信息
            </button>
        </div>
        <table id="table"></table>
    </div>
    
    <!-- 模态框（Modal） 查看-->
    <div class="modal fade" id="viewModal" tabindex="-1" role="dialog" aria-labelledby="viewModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="background: white; height: 75%;width: 80%;margin: auto;">
            <div class="modal-content" style="background: white; height: 95%;width: 95%;margin: auto;">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal" aria-hidden="true">
                        &times;
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group" style="margin-top:15px">
                        <div class="row row-gap">
                            <label class="control-label col-sm-2 label-font" for="txt_search_order_number" title="采购单号">采购单号</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="txt_search_order_number">
                            </div>
    
                            <label class="control-label col-sm-2 label-font" for="txt_search_house_name" title="仓库名称">仓库名称</label>
                            <div class="col-sm-4">
                                <select class="form-control" id="txt_search_house_name">
                                </select>
                            </div>
                        </div>
    
                        <div class="row row-gap">
                            <label class="control-label col-sm-2 label-font" for="txt_search_item_name_view" title="品名/磁棒/尺寸(材质">品名/磁棒/尺寸(材质)</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="txt_search_item_name_view">
                            </div>
    
                            <label class="control-label col-sm-2 label-font" for="txt_search_spec_view" title="规格/初R值/电阻线(线径)">规格/初R值/电阻线(线径)</label>
                            <div class="col-sm-4">
                                <input type="text" class="form-control" id="txt_search_spec_view">
                            </div>
                        </div>
    
                        <div class="row row-gap">
                            <label class="control-label col-sm-2 label-font" for="txt_search_start_time" title="开始时间">来料日期</label>
                            <div class="col-sm-4">
                                <input type="datetime-local" class="form-control" id="txt_search_start_time">
                            </div>
    
                            <label class="control-label col-sm-2 label-font" for="txt_search_end_time" title="结束时间">——</label>
                            <div class="col-sm-4">
                                <input type="datetime-local" class="form-control" id="txt_search_end_time">
                            </div>
                        </div>
    
                        <div class="row row-gap">
                            <label class="control-label col-sm-2 label-font" for="txt_search_start_storage_time" title="开始时间">入库日期</label>
                            <div class="col-sm-4">
                                <input type="datetime-local" class="form-control" id="txt_search_start_storage_time">
                            </div>
    
                            <label class="control-label col-sm-2 label-font" for="txt_search_end_storage_time" title="结束时间">——</label>
                            <div class="col-sm-4">
                                <input type="datetime-local" class="form-control" id="txt_search_end_storage_time">
                            </div>
                        </div>
    
                        <div class="row row-gap">
                            <div class="col-sm-offset-4" style="text-align:left;">
                                <button type="button" style="margin-left:50px" id="btn_filter_view" class="btn btn-primary" onclick="filterView();">过滤</button>
                                <button type="button" style="margin-left:50px" id="btn_reset_filter_view" class="btn btn-primary" onclick="clearView();">重置过滤</button>
                            </div>
                        </div>
                    </div>
                </div>
                <table id="ViewTable"></table>
            </div>
        </div>
    </div>
    
    <!-- 模态框（Modal） 新增 -->
    <div class="modal fade" id="addModal" tabindex="-1" role="dialog" aria-labelledby="addModalLabel" aria-hidden="true">
        <div class="modal-dialog" style="min-width: 800px">
            <div class="modal-content">
                <div class="modal-header">
                    <h2 class="modal-title text-center" id="addModalLabel">
                        生产出库
                    </h2>
                </div>
                <div class="modal-body">
                    <form class="form-horizontal" role="form" onsubmit="return false;">
                        <div class="form-group has-error">
                            <label class="col-sm-2 control-label" for="input_export_number">出库单号</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="input_export_number" title="该输入项不能为空" onchange="checkInputChange('input_export_number');">
                            </div>
                        </div>
                        <div class="form-group has-error">
                            <label class="col-sm-2 control-label" for="input_export_date">出库日期</label>
                            <div class="col-sm-10">
                                <input type="date" class="form-control" id="input_export_date" title="该输入项不能为空" onchange="checkInputChange('input_export_date');">
                            </div>
                        </div>
                        <div class="form-group has-error">
                            <label class="col-sm-2 control-label" for="process_select">制造流程单</label>
                            <div class="col-sm-10">
                                <select class="selectpicker form-control" id="process_select" title="该输入项不能为空" onchange="addProcessSelectChange();">
                                </select>
                            </div>
                        </div>
                        <div class="form-group has-error">
                            <label class="col-sm-2 control-label" for="material_select">出库原材料</label>
                            <div class="col-sm-10">
                                <select class="selectpicker form-control" id="material_select" title="该输入项不能为空" onchange="setInputSuccess($materialInventorySelect);" multiple>
                                </select>
                            </div>
                        </div>
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label" for="input_issue_number">发料数量</label>
                            <div class="col-sm-10">
                                <input type="text" class="form-control" id="input_issue_number" title="该输入项不能为空" onchange="issueNumberInputChange('input_issue_number');">
                            </div>
                        </div>
                        <div class="form-group has-success">
                            <label class="col-sm-2 control-label" for="input_remark">备注</label>
                            <div class="col-sm-10">
                                <textarea class="form-control" rows="6" id="input_remark"></textarea>
                            </div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-success" onclick="add();">添加</button>
                </div>
            </div><!-- /.modal-content -->
        </div><!-- /.modal -->
    </div>


<!-- JavaScript files-->
<!-- jquery.js -->
<script src="../../static/js/lib/jquery.min.js" th:src="@{/js/lib/jquery.min.js}"></script>
<!-- Bootstrap.js -->
<script src="../../static/js/lib/bootstrap3.4.1.min.js" th:src="@{/js/lib/bootstrap3.4.1.min.js}"></script>
<!-- Bootstrap-table.js -->
<script src="../../static/js/lib/bootstrap-table.min.js" th:src="@{/js/lib/bootstrap-table.min.js}"></script>
<script src="../../static/js/lib/bootstrap-table-zh-CN.min.js" th:src="@{/js/lib/bootstrap-table-zh-CN.min.js}"></script>
<!-- sweetalert2.js -->
<script src="../../static/js/lib/sweetalert.min.js" th:src="@{/js/lib/sweetalert.min.js}"></script>
<script src="../../static/js/lib/es6-promise.auto.min.js" th:src="@{/js/lib/es6-promise.auto.min.js}"></script>
<!-- jquery-ui.js -->
<script src="../../static/js/lib/jquery-ui.min.js" th:src="@{/js/lib/jquery-ui.min.js}"></script>
<!-- select2.js -->
<script src="../../static/js/lib/select2.min.js" th:src="@{/js/lib/select2.min.js}"></script>
<script src="../../static/js/lib/Select2-zh-CN.js" th:src="@{/js/lib/Select2-zh-CN.js}"></script>
<script src="../../static/js/common.js" th:src="@{/js/common.js}"></script>
<script src="../../static/js/dragModel.js" th:src="@{/js/dragModel.js}"></script>
<script>
    /** 初始化 */
    let $table = $('#table');
    let $ViewTable = $('#ViewTable');
    let $processSelect = $("#process_select");
    let $materialInventorySelect = $("#material_select");
    let $issueNumberInput = $("#input_issue_number");

    // 服务器分页获取数据
    function getServerPaging(node, url, queryParams) {
        initTable(node, url, [10, 20, 30, 40, 50, 60, "All"], queryParams, [{
            checkbox: true
        }, {
            field: 'code',
            title: '供应商代号',
            width: '90px',
            formatter: stringFormatter
        }, {
            field: 'itemName',
            title: '品名／磁棒／尺寸(材质)',
            width: '150px',
            formatter: stringFormatter
        }, {
            field: 'spec',
            title: '规格/初R值/电阻线(线径)',
            width: '150px',
            formatter: stringFormatter
        }, {
            field: 'leftAmount',
            title: '库存数量',
            width: '72px',
            formatter: stringFormatter
        }, {
            field: 'waitNumber',
            title: '待出库制造流程单号',
            width: '90px',
            formatter: stringFormatter
        }, {
            field: 'operation',
            title: '操作',
            width: '90px',
            formatter: operateFormatter // 自定义方法，添加操作按钮
        }]);
    }

    function operateFormatter(value, row, index) {  // 赋予的参数{
        return [
            '<button class="btn btn-success view" data-toggle="modal" data-target="#viewModal" onclick="view('+ index +');">查看</button>'
        ].join('');
    }

    // 服务器分页获取数据
    function getServerPagingView(node, url, queryParams) {
        initTable(node, url, [10, 20, 30, 40, 50, 60, "All"], queryParams, [{
            checkbox: true
        }, {
            field: 'code',
            title: '供应商代号',
            width: '90px',
            formatter: stringFormatter
        }, {
            field: 'orderNumber',
            title: '采购单号',
            width: '170px',
            formatter: stringFormatter
        }, {
            field: 'inDate',
            title: '来料日期',
            width: '170px',
            formatter: dateFormatter
        }, {
            field: 'inStorageDate',
            title: '入库日期',
            width: '170px',
            formatter: dateFormatter
        }, {
            field: 'itemName',
            title: '品名／磁棒／尺寸(材质)',
            width: '170px',
            formatter: stringFormatter
        }, {
            field: 'spec',
            title: '规格/初R值/电阻线(线径)',
            width: '170px',
            formatter: stringFormatter
        }, {
            field: 'leftAmount',
            title: '库存数量',
            width: '120px',
            formatter: stringFormatter
        }, {
            field: 'inAmount',
            title: '入库数量',
            width: '120px',
            formatter: stringFormatter
        }, {
            field: 'unitPrice',
            title: '单价',
            width: '120px',
            formatter: stringFormatter
        }, {
            field: 'unit',
            title: '单位',
            width: '72px',
            formatter: stringFormatter
        }, {
            field: 'jine',
            title: '金额',
            width: '140px',
            formatter: stringFormatter
        }, {
            field: 'houseName',
            title: '仓库名称',
            width: '120px',
            formatter: stringFormatter
        }], null);
    }

    // 修改提示框样式
    changeToolTip();

    // 模态框初始化
    dragTheModalDialog();

    // 仓库名称下拉框初始化
    let $searchWarehouseSelect = $("#txt_search_house_name");
    function initWareHouseSelect() {
        noParameterPostRequest("/warehouse-management/getWarehouse?limit=100&offset=0&sort=create_time&order=DESC", result => {
            $searchWarehouseSelect.empty();
            $searchWarehouseSelect.append("<option value='--请选择--'>--请选择--</option>");
            result.module.rows.forEach(item => $searchWarehouseSelect.append("<option value="+ item.name +">" + item.name + "</option>"));
        }, "GET");
    }

    // 初始化数据信息
    function init() {
        getServerPaging($table, "/material-repertory/getMaterialRepertory", params => {
            return { limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC" };
        });
        initWareHouseSelect();
    }

</script>
<script>
    /* 页面逻辑*/
    // 下拉框改变
    function addProcessSelectChange() {
        setInputSuccess($processSelect);
        // 同时改变发料数量
        console.info($processSelect.select2('data'));
        let issueNumber = $processSelect.select2('data')[0].everyAmount;
        $issueNumberInput.val(parseFloat(issueNumber).toFixed(2));
    }
    function issueNumberInputChange() {
        $issueNumberInput.val(parseFloat($issueNumberInput.val()).toFixed(2));
    }
</script>
<script>
    /** 功能 */
    // 过滤
    function filter() {
        let data = { itemName: $("#txt_search_item_name").val(), spec: $("#txt_search_spec").val() };
        if ("" === data["spec"] && "" === data["itemName"]) {
            swal("操作提示", "请填写过滤参数", "info");
            return;
        }

        getServerPaging($table, "/material-repertory/getMaterialRepertoryByConditions", params => {
            let result = { limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC", itemName: data["itemName"], spec: data["spec"]};
            removeEmptyField(result);
            return result;
        });
    }

    // 查看
    // 全局变量，点击查看时将id赋值给MasterId
    let materialInventoryMasterId;
    function view(index) {
        let rows = $('#table').bootstrapTable('getData');
        materialInventoryMasterId = rows[index].id;
        getServerPagingView($ViewTable, "/material-inventory/getMaterialInventory", params => {
            return { materialInventoryMasterId:materialInventoryMasterId, limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC" };
        });
    }

    // (查看)过滤
    function filterView() {
        let time = [$("#txt_search_start_time"), $("#txt_search_end_time")];
        let storageDateTime = [$("#txt_search_start_storage_time"), $("#txt_search_end_storage_time")];
        if ("" !== time[0][0].validationMessage || "" !== time[1][0].validationMessage || "" !== storageDateTime[0][0].validationMessage || "" !== storageDateTime[1][0].validationMessage) {
            swal("操作提示", "请填写完整的时间", "info");
            return;
        }

        let data = { orderNumber: $("#txt_search_order_number").val(), houseName: $("#txt_search_house_name").val(), itemName: $("#txt_search_item_name_view").val(),
            spec: $("#txt_search_spec_view").val(), startTime: time[0].val(), endTime: time[1].val(), startStorageDateTime: storageDateTime[0].val(), endStorageDateTime: storageDateTime[1].val() };

        if ("" === data["spec"] && "" === data["orderNumber"] && "" === data["startStorageDateTime"] && "" === data["endStorageDateTime"]
            && "--请选择--" === data["houseName"] && "" === data["startTime"] && "" === data["endTime"] && "" === data["itemName"]) {
            swal("操作提示", "请填写过滤参数", "info");
            return;
        }

        getServerPagingView($ViewTable, "/material-inventory/getMaterialInventoryByConditions", params => {
            let result = { materialInventoryMasterId: materialInventoryMasterId, limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC", itemName: data["itemName"], spec: data["spec"],
                orderNumber: data["orderNumber"], endStorageDateTime: data["endStorageDateTime"],  startStorageDateTime: data["startStorageDateTime"], houseName: data["houseName"], startTime: data["startTime"], endTime: data["endTime"] };

            if ("--请选择--" === result["houseName"]) {
                delete result["houseName"];
            }

            removeEmptyField(result);
            return result;

        });
    }
    // (查看)重置过滤
    function clearView() {
        getServerPagingView($ViewTable, "/material-inventory/getMaterialInventory", params => {
            return { materialInventoryMasterId: materialInventoryMasterId, limit: params.limit, offset: params.offset, sort: "create_time", order: "DESC" };
        });
    }

    let inStorageData = [];
    let i = 0;
    let addMaterialInventoryMasterId;
    // 生产入库
    function InAdd() {
        let data = $table.bootstrapTable('getSelections');
        if (data.length !== 1) {
            swal("操作提示", "请选择一条记录", "info");
        } else {
            $('#addModal').modal('show');

            addMaterialInventoryMasterId = data[0].id;

            initSelect($processSelect, "请输入工作传票号码", processFormatter, "/manufacturing-process-sheet/getManufactureProcessSlaveByMaterialInventoryMasterId", 1000, params => {
                return { materialInventoryMasterId: data[0].id, jobTicketNumber: params.term, offset: params.page ? 10 * (params.page - 1) : 0, limit: 10 };
            }, result => result.module.rows.map(item => {
                return { id: item.id, text: item.jobTicketNumber, code: item.code, everyAmount: item.everyAmount, spec: item.spec, itemName: item.itemName};
            }), 10);
            function processFormatter(result) {
                return '<span title="' + "客户代码：" + result.code + " | " + "工作传票号码：" + result.text + " | " + "每单投产数量：" + result.everyAmount + "| " + "品名：" + result.itemName +"| " + "材质：" + result.spec +'" >'   + result.text + '</span>';
            }

            inStorageData = [];
            i = 0;
            initSelect($materialInventorySelect, "请输入材料入库日期", materialFormatter, "/material-inventory/getMaterialInventory", 1000, params => {
                return { materialInventoryMasterId:data[0].id, inStorageDate: params.term, offset: params.page ? 10 * (params.page - 1) : 0, limit: 10 };
            }, result => result.module.rows.map(item => {
                inStorageData[i++] = item.inStorageDate;
                return { id: item.id, itemName: item.itemName, text: formatDateTime(item.inStorageDate), spec: item.spec, leftAmount: item.leftAmount};
            }), 10);
            function materialFormatter(result) {
                return '<span title="' +"品名：" + result.itemName + " | " + "规格：" + result.spec + " | " + "库存数量：" + result.leftAmount + "|" + "来料日期：" + result.text + '" >'   + result.itemName + '|'   + result.leftAmount + '|'+ result.text + '</span>';
            }
        }
    }

    function add() {
        if (0 !== $processSelect.select2('data').length) {
            let data = {};
            data.materialExportDO = {
                materialInventoryMasterId: addMaterialInventoryMasterId,
                manufactureProcessSlaveId: $processSelect.select2('data')[0].id,
                number: $("#input_export_number").val(),
                date: $("#input_export_date").val(),
                issueNumber: $issueNumberInput.val()
            };
            data.materialInventoryIds = [];

            let selectAmount = "0";
            let $materialInventorySelects = $materialInventorySelect.select2('data');
            for (let m = 0; m < $materialInventorySelects.length ; ++m) {
                data.materialInventoryIds[m] = $materialInventorySelects[m].id;
                selectAmount = parseFloat(selectAmount) + parseFloat($materialInventorySelects[m].leftAmount) ;
            }
            if ( "" === data.materialExportDO.number || "" === data.materialExportDO.date || "" === data.materialExportDO.issueNumber  || "" === data.materialExportDO.materialInventoryMasterId) {
                swal("操作提示", "请输入必输入项！", "info");
            } else if (parseFloat(selectAmount) < parseFloat(data.materialExportDO.issueNumber)) {
                swal("操作提示", "选中数量小于出库数量！", "info");
            } else {
                let min = $materialInventorySelects[0].text;
                for (let k = 0 ; k < $materialInventorySelect.select2('data').length; ++k) {
                    if (Date.parse(min.replace(/-/g,"/")) > Date.parse(($materialInventorySelect.select2('data')[k].text).replace(/-/g,"/"))) {
                        min = $materialInventorySelect.select2('data')[k].text;
                    }
                }
                for (let j = 0 ; j < i; j++) {
                    if(Date.parse(formatDateTime(min.replace(/-/g,"/"))) > Date.parse(formatDateTime((inStorageData[j])).replace(/-/g,"/"))){
                        swal("操作提示", "请按照入库顺序出库！", "info");
                        break;
                    }
                    dialog("系统将自动为您分配出库原材料，您确定要执行操作吗？", () => {
                        parameterPostRequest("/material-repertory/insert", data, () => {
                            $('#addModal').modal('hide');
                            swal("正确", "出库成功", "success");
                            i = 0;
                            init();
                        });
                    });
                }
            }
        } else {
            swal("操作提示", "请输入必输入项", "info");
        }
    }

    // 导出excel
    function exportExcel() {
        let selections = $table.bootstrapTable('getSelections');
        if (selections.length === 0) {
            swal("操作提示", "请选择记录", "info");
        } else {
            parameterPostRequest("/material-repertory/exportExcel", selections, () => loadFile("原材料库存信息.xlsx"));
        }
    }

    // 导出exportDetailExcel
    function exportDetailExcel() {
        let selections = $table.bootstrapTable('getSelections');
        if (selections.length === 0) {
            swal("操作提示", "请选择记录", "info");
        } else {
            parameterPostRequest("/material-repertory/exportDetailExcel", selections, () => loadFile("原材料库存详细信息.xlsx"));
        }
    }
</script>

</body>

</html>